from rest_framework import serializers
from django_redis import get_redis_connection


class CheckImageCodeSerializer(serializers.Serializer):
    image_code_id = serializers.UUIDField()
    text = serializers.CharField(max_length=4, min_length=4)

    def validate(self, attrs):
        # 连接存放验证码的redis
        redis_connection = get_redis_connection('verify_codes')
        # 获取前端传过来的image_code_id对应的验证码真实值
        real_image_code_text = redis_connection.get('img_{}'.format(attrs['image_code_id']))
        # 如果不存在代表过期或无效的图片验证码id
        if real_image_code_text is None:
            raise serializers.ValidationError('图片验证码无效')
        else:
            real_image_code_text = real_image_code_text.decode()
        redis_connection.delete('img_{}'.format(attrs['image_code_id']))
        # 如果不相等代表用户输入的图片验证码错误
        if real_image_code_text.upper() != attrs['text'].upper():
            raise serializers.ValidationError('图片验证码错误')
        # 判断60秒内是否已经发送过短信验证码
        mobile = self.context['view'].kwargs['mobile']
        # 获取本次请求发送短信验证码手机号的60秒标记值
        send_flag = redis_connection.get('send_flag_{}'.format(mobile))
        # 如果有代表在60秒内向该手机号发送过短信验证码
        if send_flag:
            raise serializers.ValidationError('请求次数过于频繁')
        return attrs

